class QueueManager {
    constructor(maxConcurrentJobs = 5) {
        this.maxConcurrentJobs = maxConcurrentJobs;
        this.activeJobs = new Map();
        this.pendingJobs = new Map();
        this.completedJobs = new Map();
        this.failedJobs = new Map();
    }

    // 添加任务到队列
    async addJob(jobId, task) {
        console.log(`添加任务到队列: ${jobId}`);
        
        // 创建任务包装器
        const wrappedTask = async () => {
            try {
                console.log(`开始执行任务: ${jobId}`);
                this.activeJobs.set(jobId, { status: 'processing', startTime: Date.now() });
                
                const result = await task();
                
                console.log(`任务完成: ${jobId}`);
                this.completedJobs.set(jobId, {
                    status: 'completed',
                    result,
                    endTime: Date.now()
                });
                
                return result;
            } catch (error) {
                console.error(`任务失败: ${jobId}`, error);
                this.failedJobs.set(jobId, {
                    status: 'failed',
                    error: error.message,
                    endTime: Date.now()
                });
                throw error;
            } finally {
                this.activeJobs.delete(jobId);
                this.processNextJob();
            }
        };

        // 将任务添加到待处理队列
        this.pendingJobs.set(jobId, wrappedTask);
        console.log(`任务已加入待处理队列: ${jobId}`);
        
        // 尝试处理下一个任务
        this.processNextJob();
        
        return jobId;
    }

    // 处理下一个任务
    async processNextJob() {
        if (this.activeJobs.size >= this.maxConcurrentJobs) {
            console.log(`当前活跃任务数(${this.activeJobs.size})已达到最大并发数(${this.maxConcurrentJobs})`);
            return;
        }

        if (this.pendingJobs.size === 0) {
            console.log('没有待处理的任务');
            return;
        }

        // 获取下一个待处理任务
        const [nextJobId, nextTask] = this.pendingJobs.entries().next().value;
        this.pendingJobs.delete(nextJobId);

        // 执行任务
        try {
            await nextTask();
        } catch (error) {
            console.error(`任务执行失败: ${nextJobId}`, error);
        }
    }

    // 获取任务状态
    getJobStatus(jobId) {
        if (this.activeJobs.has(jobId)) {
            return this.activeJobs.get(jobId);
        }
        if (this.pendingJobs.has(jobId)) {
            return { status: 'pending' };
        }
        if (this.completedJobs.has(jobId)) {
            return this.completedJobs.get(jobId);
        }
        if (this.failedJobs.has(jobId)) {
            return this.failedJobs.get(jobId);
        }
        return null;
    }

    // 获取队列状态
    getQueueStatus() {
        return {
            active: this.activeJobs.size,
            pending: this.pendingJobs.size,
            completed: this.completedJobs.size,
            failed: this.failedJobs.size
        };
    }

    // 取消任务
    cancelJob(jobId) {
        if (this.pendingJobs.has(jobId)) {
            this.pendingJobs.delete(jobId);
            console.log(`任务已取消: ${jobId}`);
            return true;
        }
        return false;
    }
}

module.exports = QueueManager; 